const { db, query } = require("../../db/db");
const util = require("util");

async function GetActivityList(req, res) {
  let PageSize = req.body.PageSize;
  let PageNum = req.body.PageNum;
  let Type = req.body.Type;
  let Filter = req.body.Filter;
  let UserId = Number(Number(req.params.username));

  let sql_condition = "";

  if (!PageSize) {
    PageSize = 10;
  }
  if (!PageNum) {
    PageNum = 1;
  }

  if (!(Filter == undefined || Filter == "")) {
    if (!(Type == undefined || Type == "")) {
      sql_condition += util.format(
        "Where a.ActivityTitle like '%%%s%%' AND a.ActivityType=%s",
        Filter,
        Type
      );
    } else {
      sql_condition += util.format(
        "Where a.ActivityTitle like '%%%s%%'",
        Filter
      );
    }
  } else {
    if (!(Type == undefined || Type == "")) {
      sql_condition += util.format("Where a.ActivityType=%s", Type);
    }
  }

  const select_Activity_list_sql = util.format(
    "Select \
    a.ActivityId, \
    IFNULL(a.ActivityTitle,'') as ActivityTitle, \
    IFNULL(a.ActivityContent,'') as ActivityContent, \
    IFNULL(u.UserName,'') as PublisherName, \
    a.ActivityType \
    From Ativity a LEFT JOIN User u\
    ON a.CreateUserId=u.UserId \
    %s ORDER BY a.CreateTime Desc Limit %s,%s",
    sql_condition,
    (PageNum - 1) * PageSize,
    PageSize
  );

  const select_Activity_list_res = await query(select_Activity_list_sql);

  //获取全部总数量
  const select_Activity_list_sql_count = util.format(
    "Select \
    COUNT(*) as count \
    From Ativity a LEFT JOIN User u\
    ON a.CreateUserId=u.UserId\
    %s",
    sql_condition
  );

  const select_Activity_list_res_count = await query(
    select_Activity_list_sql_count
  );
  res.send({
    status: 0,
    ActivityList: select_Activity_list_res,
    TotalCount: select_Activity_list_res_count[0].count,
  });
}

module.exports = { GetActivityList };
